package com.ruoyi.common.scheduler;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.scheduler.domain.vo.DataImportVo;
import com.ruoyi.common.scheduler.mapper.DataImportReportMapper;
import com.ruoyi.common.tools.utils.DateUtils;
import com.ruoyi.common.utils.wx.SendWxCpMsgUtil;
import com.ruoyi.system.service.ISysUserService;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;

@Slf4j
@RequiredArgsConstructor
@Component
public class DataImportReportScheduler {
	private final DataImportReportMapper dataImportReportMapper;
	private final ISysUserService sysUserService;
    @Value("${wechat.cp.appConfigs[0].agentId}")
    private Integer agentId;

	@Value("${spring.profiles.active}")
	private String env;

	@Scheduled(cron = "0 30 10 * * ?")
	public void stat() {
		log.info("start data import report task. env : {}, agentId: {}", env, agentId);

		String queryTime = DateUtils.getPreDate(1);

		List<DataImportVo> dataImportList = dataImportReportMapper.getDataImportStatus(queryTime);
		DataImportVo toiletImportVo = dataImportReportMapper.getToiletImportStatus(queryTime);

		dataImportList.add(toiletImportVo);

		dataImportList.sort(new Comparator<DataImportVo>(){
		    @Override
		    public int compare(DataImportVo v1, DataImportVo v2) {
		    	if (v2 == null) {
		    		return v1.getBusnessIndex();
		    	} else {
		    		return v1.getBusnessIndex() - v2.getBusnessIndex();
		    	}
		    }
		});

		List<SysUser> userList = sysUserService.selectDataImportRecipients();

		String msg = generateMessage(dataImportList, queryTime);

		for (SysUser sysUser : userList) {
			sendMsg(agentId, msg, sysUser, queryTime);
		}
	}

	private void sendMsg(int agentId, String msg, SysUser sysUser, String date) {
		for (int times = 0; times < 3; times++) {
			try {
				msg = String.format(msg, date);

				log.debug("微信数据上传结果上报内容：{}", msg);

				String result = SendWxCpMsgUtil.sendTextMsgByUserPhoneNum(agentId, sysUser.getPhonenumber(), msg);

				log.debug("微信数据上传结果上报返回结果：{}", result);

				break;
			} catch (WxErrorException ex) {
				ex.printStackTrace();
				log.error("微信数据上传结果上报失败，失败原因：{}", ex.getMessage());
			}
		}
	}

	private String generateMessage(List<DataImportVo> dataImportList, String queryTime) {
		StringBuffer buffer = new StringBuffer();

		buffer.append(String.format("昨日 %s 台账导入情况如下：\r\n", queryTime));

		int importedCount = 0;
		int unimportedCount = 0;
		for (DataImportVo vo : dataImportList) {
			if (vo.getImportFlag() == 1) {
				buffer.append(String.format("【%s】 %s：", vo.getBusinessNameCn(), "已导入") + "\r\n");
				buffer.append(String.format("导入用户： %s；", getOperator(vo.getOperator())) + "\r\n");
				buffer.append(String.format("导入条数： %d；", vo.getImportCount()) + "\r\n");
				importedCount++;
			} else {
				buffer.append(String.format("【%s】 %s；", vo.getBusinessNameCn(), "未导入") + "\r\n");
				unimportedCount++;
			}
		}

		buffer.append(String.format("共计%d个已导入，%d个未导入。", importedCount, unimportedCount));

		return buffer.toString();
	}

	private String getOperator(String operatorSet) {
		if (StringUtils.isBlank(operatorSet)) {
			return "";
		} else {
			return operatorSet.substring(0, operatorSet.length() - 1);
		}
	}
}
